<template>
  <div>

    <div class="container">
      <div class="handle-box">
        <el-input v-model="query.conferenceName" clearable placeholder="会议名称" style="width: 200px;" class="handle-input mr10"></el-input>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        <el-button type="primary" icon="el-icon-plus" @click="addVisible = true">新增</el-button>
        <!-- ✅ 导入导出按钮 -->
        <!-- <el-button
          type="success"
          icon="el-icon-upload2"
          class="mr10"
          @click="$refs.excelInput.click()"
        >导入 Excel</el-button> -->
        <input
          type="file"
          ref="excelInput"
          style="display: none"
          accept=".xlsx, .xls"
          @change="importFromExcel"
        />
        <el-button
          type="warning"
          icon="el-icon-download"
          @click="exportToExcel"
        >导出 Excel</el-button>
        <el-button type="danger" icon="el-icon-delete" @click="handleBatchDelete" :disabled="multipleSelection.length === 0">批量删除</el-button>
      </div>

      <el-table
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column prop="conferenceName" label="会议名称"></el-table-column>
        <!-- <el-table-column prop="imgUrl" label="图标"></el-table-column> -->
        <el-table-column label="图片">
          <template slot-scope="scope">
            <el-image
              style="width: 100px; height: 100px"
              :src="scope.row.imgUrl"
              :preview-src-list="[scope.row.imgUrl]"
              fit="cover"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="conferenceLocation" label="会议地点"></el-table-column>
        <el-table-column prop="organizerContact" label="主办方联系方式"></el-table-column>
        <el-table-column prop="startDate" label="开始时间" :formatter="formatDateTime"></el-table-column>
        <el-table-column prop="endDate" label="结束时间" :formatter="formatDateTime"></el-table-column>
        <el-table-column label="会议状态" prop="status">
          <template #default="scope">
            <span>{{ scope.row.status === 1 ? '有效' : '无效' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="会议描述"></el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(scope.row)"
            >编辑</el-button>
            <el-button
              type="text"
              icon="el-icon-delete"
              class="red"
              @click="handleDelete(scope.row.conferenceId)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :current-page="query.pageIndex"
          :page-size="query.pageSize"
          :total="pageTotal"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>

    <!-- 编辑弹出框 -->
    <el-dialog title="编辑" :visible.sync="editVisible" width="40%">
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="会议名称" prop="conferenceName">
          <el-input v-model="form.conferenceName" placeholder="请输入会议名称" />
        </el-form-item>
      
        <el-form-item label="会议地点" prop="conferenceLocation">
          <el-input v-model="form.conferenceLocation" placeholder="请输入会议地点" />
        </el-form-item>
      
        <el-form-item label="联系方式" prop="organizerContact">
          <el-input v-model="form.organizerContact" placeholder="请输入主办方联系方式" />
        </el-form-item>
      
        <el-form-item label="开始时间" prop="startDate">
          <el-date-picker v-model="form.startDate" type="datetime" placeholder="选择开始时间" />
        </el-form-item>
      
        <el-form-item label="结束时间" prop="endDate">
          <el-date-picker v-model="form.endDate" type="datetime" placeholder="选择结束时间" />
        </el-form-item>
      
        <el-form-item label="会议状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择会议状态">
            <el-option label="有效" :value="1"></el-option>
            <el-option label="无效" :value="0"></el-option>
          </el-select>
        </el-form-item>
      
        <el-form-item label="会议描述" prop="description">
          <el-input type="textarea" v-model="form.description" placeholder="请输入会议描述" />
        </el-form-item>

        <el-form-item label="上传图片" prop="imageList">
          <el-upload
            action="#"
            :http-request="uploadToOSS"
            list-type="picture-card"
            :file-list="form.imageList"
            :on-remove="handleImageRemove"
            :on-preview="handleImagePreview"
            multiple
            ref="upload"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>

      </el-form>
    
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelEdit">取 消</el-button>
        <el-button type="primary" @click="saveEdit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 新增弹出框 -->
    <el-dialog title="新增" :visible.sync="addVisible" width="40%">
      <el-form
        ref="form"
        :model="addForm"
        :rules="rules"
        label-width="100px"
      >
        <!-- 会议相关字段 -->
        <el-form-item label="会议名称" prop="conferenceName">
          <el-input v-model="addForm.conferenceName" placeholder="请输入会议名称" />
        </el-form-item>
      
        <el-form-item label="会议地点" prop="conferenceLocation">
          <el-input v-model="addForm.conferenceLocation" placeholder="请输入会议地点" />
        </el-form-item>
      
        <el-form-item label="联系方式" prop="organizerContact">
          <el-input v-model="addForm.organizerContact" placeholder="请输入主办方联系方式" />
        </el-form-item>
      
        <el-form-item label="开始时间" prop="startDate">
          <el-date-picker v-model="addForm.startDate" type="datetime" placeholder="选择开始时间" />
        </el-form-item>
      
        <el-form-item label="结束时间" prop="endDate">
          <el-date-picker v-model="addForm.endDate" type="datetime" placeholder="选择结束时间" />
        </el-form-item>
      
        <el-form-item label="会议状态" prop="status">
          <el-select v-model="addForm.status" placeholder="请选择会议状态">
            <el-option label="有效" :value="1"></el-option>
            <el-option label="无效" :value="0"></el-option>
          </el-select>
        </el-form-item>
      
        <el-form-item label="会议描述" prop="description">
          <el-input type="textarea" v-model="addForm.description" placeholder="请输入会议描述" />
        </el-form-item>
      </el-form>
    
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelAdd">取 消</el-button>
        <el-button type="primary" @click="saveAdd">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible" width="50%">
      <img :src="dialogImageUrl" alt="" style="width: 100%" />
    </el-dialog>

  </div>
</template>

<script>
import * as XLSX from 'xlsx';
import requests from '../utils/request'
import dayjs from 'dayjs';


export default {
    name: 'basetable',
    data() {
      return {
        dialogImageUrl: '',
        dialogVisible: false,
        query: {
            conferenceName: '',
            pageIndex: 1,
            pageSize: 30
        },
        tableData: [],
        multipleSelection: [],
        exportData: [],
        editVisible: false,
        addVisible: false,
        pageTotal: 0,
        form: {
          conferenceId: '',
          conferenceName: '',
          conferenceLocation: '',
          organizerContact: '',
          startDate: '',
          endDate: '',
          status: 1,
          description: '',
          imageUrl: '',
          imageList: []
        },
        hotels:{},
        users:{},
        addForm: {
          conferenceName: '',
          conferenceLocation: '',
          organizerContact: '',
          startDate: '',
          endDate: '',
          status: null,
          description: '',
        },
        idx: -1,
        id: -1,
        rules: {
          conferenceName: [
            { required: true, message: '请输入会议名称', trigger: 'blur' }
          ],
          conferenceLocation: [
            { required: true, message: '请输入会议地点', trigger: 'blur' }
          ],
          organizerContact: [
            { required: true, message: '请输入主办方联系方式', trigger: 'blur' },
            {
              pattern: /^(1[3-9]\d{9}|0\d{2,3}-?\d{7,8})$/,
              message: '请输入正确的手机号或座机号',
              trigger: 'blur'
            }
          ],
          startDate: [
            { required: true, message: '请选择开始时间', trigger: 'change' }
          ],
          endDate: [
            { required: true, message: '请选择结束时间', trigger: 'change' }
          ],
          status: [
            { required: true, message: '请选择会议状态', trigger: 'change' }
          ],
        }
      };
    },
    created() {
       this.loading()
    },
    methods: {
      //加载数据
      loading() {
        requests.get("/conferences/pageSelect", {
          page: this.query.pageIndex,
          size: this.query.pageSize,
          conferenceName: this.query.conferenceName
        }).then(res=>{
          this.pageTotal = res.total,
          this.tableData = res.data
        });
      },
      // 触发搜索按钮
      handleSearch() {
          this.loading();
      },
      //时间处理
      formatDateTime(row, column, cellValue) {
        if (!cellValue) return '';
        const date = new Date(cellValue);
        const pad = n => n.toString().padStart(2, '0');
        return `${date.getFullYear()}/${pad(date.getMonth() + 1)}/${pad(date.getDate())} ` +
               `${pad(date.getHours())}:${pad(date.getMinutes())}`;
      },
      // 删除操作
      handleDelete(row) {
        // 二次确认删除
        this.$confirm('确定要删除吗？', '提示', {
            type: 'warning'
        })
            .then(() => {
                requests.delete("/conferences/delById",{
                  conferenceId: row
                }).then(res=>{
                  this.$message.success(res);
                  this.loading()
                })
            })
            
      },
      // 编辑操作
      handleEdit(row) {
        // 安全深拷贝 row 对象，避免响应式污染
        const newForm = JSON.parse(JSON.stringify(row));
        // 赋值给表单
        this.form = newForm;
        if (!this.form.imageList && this.form.imgUrl) {
          this.form.imageList = [{ name: '封面图.jpg', url: this.form.imgUrl }];
        } else if (!this.form.imageList) {
          this.form.imageList = [];
        }
        this.editVisible = true;
      },
      // 取消编辑
      cancelEdit() {
        // 失去当前聚焦
        document.activeElement && document.activeElement.blur();
      
        this.editVisible = false;
        // 重置表单（如果需要）
        this.$refs.form.resetFields();
      },
      // 保存编辑
      saveEdit() {
        // 先校验表单
        this.$refs.form.validate(valid => {
          if (!valid) {
            // 校验失败，不提交
            return;
          }
          // 校验成功，调用接口
          requests.post("/conferences/edit", this.form)
            .then(res => {
              this.$message.success(res);  // 用 success 提示更合适
              this.editVisible = false;    // 请求成功后关闭弹窗
              this.loading();              // 刷新数据

            })
        });
      },
      // 分页导航
      handlePageChange(val) {
          this.query.pageIndex = val
          this.loading()
      },
      // 单选、多选改变时调用
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      // 批量删除
      handleBatchDelete() {
        if (this.multipleSelection.length === 0) {
          this.$message.warning('请选择要删除的酒店');
          return;
        }
      
        this.$confirm(`确定删除这 ${this.multipleSelection.length} 项吗？`, '提示', {
          type: 'warning'
        })
          .then(() => {
            const ids = this.multipleSelection.map(item => item.conferenceId);
            console.log(ids);
            
            requests.post('/conferences/delByIds', ids)  // ✅ 注意这里直接传数组
              .then(res => {
                this.$message.success(res);
                this.loading(); // 重新加载表格
              })

          })

      },
      //新增操作
      handleAdd(row) {
        this.addForm = row;
        this.addVisible = true;
      },
      // 取消操作
      cancelAdd() {
        // 失去当前聚焦
        document.activeElement && document.activeElement.blur();
      
        this.addVisible = false;
        // 重置表单（如果需要）
        this.$refs.addForm.resetFields();
      },
      // 保存操作
      saveAdd() {
        // 先校验表单
        this.$refs.form.validate(valid => {
          if (!valid) {
            // 校验失败，不提交
            return;
          }
          
          // // 校验成功，调用接口
          requests.post("/conferences/add", this.addForm)
            .then(res => {
              this.$message.success(res);  // 用 success 提示更合适
              this.addVisible = false;    // 请求成功后关闭弹窗
              this.loading();              // 刷新数据
            })
        });
      },
      //导出
      exportToExcel() {
        requests.get("/conferences/exportConferenceInfor").then(res => {
          // 通用时间格式化
          const formatDate = (value) => {
            if (!value) return '';
            const date = new Date(value);
            if (isNaN(date.getTime())) return '';
            return date.toLocaleString(); // 或使用自定义格式
          };      

          // 处理导出数据
          const exportData = res.map(row => ({
            // 标识: String(row.conferenceId),
            会议名称: row.conferenceName || '',
            会议地点: row.conferenceLocation || '',
            主办方联系方式: row.organizerContact || '',
            开始时间: formatDate(row.startDate),
            结束时间: formatDate(row.endDate),
            会议状态: row.status === 1 ? '有效' : '无效',
            会议描述: row.description || ''
          }));      

          // 若无数据也保留表头结构
          if (exportData.length === 0) {
            exportData.push({
              // 标识: '',
              会议名称: '',
              会议地点: '',
              主办方联系方式: '',
              开始时间: '',
              结束时间: '',
              会议状态: '',
              会议描述: ''
            });
          }     

          // 创建工作表
          const ws = XLSX.utils.json_to_sheet(exportData);      

          // 设置列宽
          ws['!cols'] = [
            // { wch: 10 }, // 标识
            { wch: 70 }, // 会议名称
            { wch: 30 }, // 会议地点
            { wch: 20 }, // 主办方联系方式
            { wch: 25 }, // 开始时间
            { wch: 25 }, // 结束时间
            { wch: 10 }, // 会议状态
            { wch: 60 }  // 会议描述
          ];      

          // 格式化时间列
          const header = Object.keys(exportData[0]);
          const keys = Object.keys(ws);     

          ['开始时间', '结束时间'].forEach(label => {
            const index = header.indexOf(label);
            if (index >= 0) {
              const colLetter = String.fromCharCode(65 + index);
              keys.forEach(key => {
                if (key.startsWith(colLetter) && key !== `${colLetter}1`) {
                  const cell = ws[key];
                  if (cell && typeof cell.v === 'string' && !isNaN(Date.parse(cell.v))) {
                    const d = new Date(cell.v);
                    cell.v = d;
                    cell.t = 'd';
                    cell.z = 'yyyy/mm/dd hh:mm';
                  }
                }
              });
            }
          });     

          // 创建并导出 Excel 文件
          const wb = XLSX.utils.book_new();
          XLSX.utils.book_append_sheet(wb, ws, '会议数据');
          XLSX.writeFile(wb, '会议信息.xlsx');
        })
      },
      //导入
      importFromExcel(e) {
        const file = e.target.files[0];
        if (!file) return;
      
        const reader = new FileReader();
        reader.onload = (event) => {
          const data = new Uint8Array(event.target.result);
          const workbook = XLSX.read(data, { type: 'array' });
        
          const firstSheetName = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[firstSheetName];
        
          // 读取为 JSON（跳过空行）
          let excelData = XLSX.utils.sheet_to_json(worksheet, { raw: false });
          excelData = excelData.filter(row =>
            Object.values(row).some(v => v != null && String(v).trim() !== '')
          );
        
          if (!excelData || excelData.length === 0) {
            this.$message.warning('Excel 中无有效数据，无法导入');
            this.$refs.excelInput.value = '';
            return;
          }
        
          // 映射字段
          const mappedData = excelData.map((row, idx) => {
            const conferenceId = Number(row['标识']);
            var statusText = row['会议状态'] ? row['会议状态'].trim() : '';
            const status = statusText === '有效' ? 1 : 0;
          
            // 时间解析
            const parseDate = (val) => {
              const date = new Date(val);
              return isNaN(date.getTime()) ? null : date.toISOString(); // 或格式化为后端接受的格式
            };
          
            const startDate = parseDate(row['开始时间']);
            const endDate = parseDate(row['结束时间']);
          
            if (isNaN(conferenceId) || !row['会议名称']) {
              console.warn(`第 ${idx + 2} 行数据无效，跳过：`, row);
              return null;
            }
          
            return {
              conferenceId,
              conferenceName: row['会议名称'],
              conferenceLocation: row['会议地点'] || '',
              organizerContact: row['主办方联系方式'] || '',
              startDate,
              endDate,
              status,
              description: row['会议描述'] || ''
            };
          }).filter(item => item !== null);
        
          if (mappedData.length === 0) {
            this.$message.warning('所有行均不符合导入要求，未生成可提交的数据');
            this.$refs.excelInput.value = '';
            return;
          }
        
          // 提交给后端接口
          requests.post('/conferences/importConferenceInfor', mappedData)
            .then(response => {
              this.$message.success(response);
              this.loading(); // 刷新列表
            })
          
          this.$refs.excelInput.value = '';
        };
      
        reader.readAsArrayBuffer(file);
      },
      //图片上传
      // 上传至阿里云 OSS
      uploadToOSS(option) {
        const file = option.file;
      
        // 获取签名
        requests.get('/files/policy', {
          conferenceId: this.form.conferenceId
        }).then(res => {
          
          const data = res;
          const fileName = Date.now() + '-' + file.name;
          const key = data.dir + fileName;
          
          const formData = new FormData();
          formData.append('key', key);
          formData.append('policy', data.policy);
          formData.append('OSSAccessKeyId', data.accessid);
          formData.append('success_action_status', '200');
          formData.append('signature', data.signature);
          formData.append('file', file);
          
          // 上传到阿里云
          requests.post(data.host, formData).then(() => {
            const url = `${data.host}/${key}`;
            if (!this.form.imageList) {
              this.form.imageList = [];
            }
            this.form.imageList.push({ url });
          
            // ✅ 触发校验
            this.$refs.form.validateField('imageList');
          
            this.$message.success('上传成功');
          })
        })
      },    
      // 移除图片（支持单张）
      handleImageRemove(file, fileList) {
        this.form.imageList = fileList;
      
        // ✅ 触发校验
        this.$refs.form.validateField('imageList');
      },
      // 预览图片
      handleImagePreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      }

    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
